package com.linkage.jz.bankruptcy.fragment.Main;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.BrowserActivity;
import com.linkage.jz.bankruptcy.activity.Main.LawDetailActivity;
import com.linkage.jz.bankruptcy.activity.Main.PDFViewActivity;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.MainbakActivity;
import com.linkage.jz.bankruptcy.adapter.LawListViewAdapter;
import com.linkage.jz.bankruptcy.bean.LawListInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.Divider;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.utils.FileUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * date : 2016/5/24
 * author : lijiawei
 */
public class DocTmpZFrgment extends Fragment implements BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener {

    //显示信息
    private TextView text;
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();
    private LawListViewAdapter mAdapter;
    private ArrayList<LawListInfo> mData;
    private RecyclerView mDataRv;
    private RelativeLayout rl_search;
    private EditText law_searchtxt;
    private PublicNoticeDialog noticeDialog;
    private TextView tv_bottom;
    private LinearLayout ll_nodata,ll_myweb;

    ArrayList<Fragment> fragments = new ArrayList<Fragment>();



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_law_list, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        initRecyclerView(view);
        getData();

    }

    private void init(View view) {
//        text = (TextView) view.findViewById(R.id.fragment_textview);
//        text.setText("GroupChildrenHasBuy");
    }

    private int showWeb(String url) {
        int ret = -1;
        try {
            Uri uri = Uri.parse(url);
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
            ret = 0;
        } catch (Exception e) {

        }
        return ret;
    }

    private void initRecyclerView(final View view) {
        mDataRv = (RecyclerView) view.findViewById(R.id.rv_recyclerview_data);
//        mDataRv.addItemDecoration(new Divider(getActivity()));
        rl_search = (RelativeLayout)view.findViewById(R.id.rl_search);
//        tv_bottom = (TextView) view.findViewById(R.id.tv_bottom);
//        tv_bottom.setVisibility(View.VISIBLE);
        ll_myweb = (LinearLayout)view.findViewById(R.id.ll_myweb);
        ll_nodata = (LinearLayout)view.findViewById(R.id.ll_nodata);
        ll_myweb.setVisibility(View.VISIBLE);
        ll_myweb.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showWeb("http://www.poxiao.com");
            }
        });
        rl_search.setVisibility(View.GONE);
        law_searchtxt = (EditText) getActivity().findViewById(R.id.law_searchtxt1);



        law_searchtxt.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override

            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {

// TODO Auto-generated method stub

                if(arg1 == EditorInfo.IME_ACTION_SEARCH)

                {
                    InputMethodManager imm = (InputMethodManager) view.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
                    }
                    ((EditText) getActivity().findViewById(R.id.law_searchtxt2)).setText(law_searchtxt.getText().toString());
                    mData.clear();
                                mAdapter.notifyDataSetChanged();

                    getData();
//                    Toast.makeText(AddMemberActivity.this,"呵呵",Toast.LENGTH_SHORT).show();

// search pressed and perform your functionality.

                }

                return false;

            }

        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataRv.setLayoutManager(layoutManager);

        mAdapter = new LawListViewAdapter(mDataRv);
        mAdapter.setOnRVItemClickListener(this);
        mAdapter.setOnRVItemLongClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemChildLongClickListener(this);

        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
        mData = new ArrayList<LawListInfo>();
//        mData = DataEngine.loadNormalModelDatas();

//        LawListInfo model = new LawListInfo();
////                                model.setId(data.getString("id"));
//        model.setTitle("11");
//        model.setContent("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1553534771679&di=2517ee53734f785e75e1240a015eaab0&imgtype=0&src=http%3A%2F%2Fimgsa.baidu.com%2Fexp%2Fw%3D500%2Fsign%3D919ca74c0d55b3199cf9827573a88286%2F1c950a7b02087bf4348ebca4f5d3572c11dfcf19.jpg");
//        mData.add(model);
//
//        LawListInfo model1 = new LawListInfo();
////                                model.setId(data.getString("id"));
//        model1.setTitle("22");
//        model1.setContent("http://res.imtt.qq.com/TES/HowToLoadX5Core.doc");
//        mData.add(model1);
        mAdapter.setData(mData);
        mDataRv.setAdapter(mAdapter);
    }

    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
            mAdapter.removeItem(position);
        }
    }

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
//            Toast.makeText(getActivity(), "长按了删除 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    String fileurl = "";
    String filename  = "";

    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {
        LawListInfo model = mAdapter.getItem(position);
        if(model !=null) {

            if(model !=null &&  model.content!=null) {
                if(model.getFileName().indexOf(".pdf") == -1) {

//                URL = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558322400&di=316ed721bee5fc86cb82f1eba9e4fe4e&imgtype=jpg&er=1&src=http%3A%2F%2Fpic37.nipic.com%2F20140113%2F8800276_184927469000_2.png";
//                String filename = model.content.substring(  model.content.lastIndexOf("/")+1, model.content.length());
//                    FileUtils.saveNetFileToSD(getActivity(),model.getFilePath() ,model.getFileName());
                    fileurl= model.getFilePath();
                    filename = model.getFileName();
                    noticeDialog = new PublicNoticeDialog(getActivity(), onClickListener,
                            1, "提示", "确定下载该文件吗？",
                            "取消", "确定");
                    noticeDialog.show();

                }else{

                    Intent intent = new Intent(getActivity(), PDFViewActivity.class);
                    intent.putExtra("url", model.getFilePath());
                    getActivity().startActivity(intent);
                }
            }
//
//            Intent intent = new Intent(getActivity(), MainbakActivity.class);
//            intent.putExtra("url",model.content);
//            getActivity().startActivity(intent);

        }

//        Toast.makeText(getActivity(), "点击了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_close:
                    noticeDialog.dismiss();

                    break;

                case R.id.btn_chancel_notice:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    noticeDialog.dismiss();

                    break;

                case R.id.btn_save_notice:
                    FileUtils.saveNetFileToSD(getActivity(),fileurl ,filename);
                    noticeDialog.dismiss();
                    break;

            }
        }
    };


    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
//        Toast.makeText(getActivity(), "长按了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }


    public void getData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        String title = law_searchtxt.getText().toString();

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("avatar", "")
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")
                .add("type","1")
                .add("title",title)
                .add("pageNumber","1")
                .add("pageSize","100")
                .build();

        String url = Consts.WEBURL_DOCTMPLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
//                runOnUiThread(new Runnable(){
//
//                    @Override
//                    public void run() {
//                        //更新UI
//                        Toast.makeText(PersonSettingOrgActivity.this,"保存失败",Toast.LENGTH_SHORT).show();
//
//                    }
//
//                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

//                shapeLoadingDialog.dismiss();


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    mData.clear();
                    if(object.optInt("code") == 0)
                    {
                        JSONObject dataobj = object.getJSONObject("data");
                        String baseUrl = dataobj.optString("baseUrl");
                        JSONObject listpage = dataobj.getJSONObject("listPage");
                        JSONArray ary = listpage.getJSONArray("list");

                        mData.clear();
//                        JSONArray ary = object.getJSONArray("list");
                        if(ary.length() == 0)
                        {
                            getActivity().runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    //更新UI
                                    ll_nodata.setVisibility(View.VISIBLE);
                                    mDataRv.setVisibility(View.GONE);
                                    mAdapter.notifyDataSetChanged();

                                }

                            });
                        }else {
                            for (int i = 0; i < ary.length(); i++) {
                                JSONObject data = ary.getJSONObject(i);
                                LawListInfo model = new LawListInfo();
//                                model.setId(data.getString("id"));
                                model.setTitle(data.getString("title"));
                                model.setFilePath(data.getString("filePath"));
                                model.setFileName(data.getString("fileName"));
                                model.setContent(baseUrl+"/"+data.getString("fileName"));
                                mData.add(model);
                            }
                            getActivity().runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    //更新UI
                                    ll_nodata.setVisibility(View.GONE);
                                    mDataRv.setVisibility(View.VISIBLE);
                                    mAdapter.notifyDataSetChanged();

                                }

                            });
                        }



//                        mAdapter.notifyDataSetChanged();

                    }else {
//                        runOnUiThread(new Runnable() {
//
//                            @Override
//                            public void run() {
//                                //更新UI
//                                Toast.makeText(PersonSettingOrgActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
//
//                            }
//
//                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
//                    runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            //更新UI
//                            Toast.makeText(PersonSettingOrgActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
//
//                        }
//
//                    });
                }
            }
        });
    }

}
